import base64

from captcha.views import CaptchaStore, captcha_image
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.views import APIView
from dvadmin.system.views.tasks import test_task, download_start

from application import dispatch

from dvadmin.utils.json_response import ErrorResponse, DetailResponse
import requests
from django.db import transaction
from dvadmin.system.models import DownloadList, DownloadInfo, MessageList as MessageModel
from urllib.parse import unquote
from django_redis import get_redis_connection
import json
from django.utils import timezone


# 获取消息列表接口
class MessageList(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="message-list",
        operation_description="获取消息列表接口",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        start_time = request_data.get("start_time", "")
        end_time = request_data.get("end_time", "")
        type = request_data.get("type", "")
        page = int(request_data.get("page", 1))

        if not start_time or not end_time or not type:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"admin_login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        page_size = 15
        message_obj = MessageModel.objects
        if start_time:
            message_obj = message_obj.filter(start_time__gte=start_time+" 00:00:00")

        if end_time:
            message_obj = message_obj.filter(start_time__lte=end_time+" 23:59:59")

        if type and int(type) != 0:
            message_obj = message_obj.filter(type=type)
        count = message_obj.count()
        res = message_obj.all()[
              page_size * (page - 1):page_size * page]

        return_data = []
        for item in res:
            _data = {}
            _data["id"] = item.id
            _data["ydh"] = item.ydh
            _data["third_ydh"] = item.third_ydh
            _data["fhdw"] = item.fhdw
            _data["shdw"] = item.shdw
            _data["start_time"] = item.start_time.strftime("%Y-%m-%d %H:%M:%S")
            _data["sign_time"] = item.sign_time.strftime("%Y-%m-%d %H:%M:%S")
            _data["temp_limit_max"] = item.temp_limit_max
            _data["temp_limit_min"] = item.temp_limit_min
            _data["temp_max"] = item.temp_max
            _data["temp_min"] = item.temp_min
            _data["remark"] = item.remark
            _data["type"] = item.type
            _data["status"] = item.status
            _data["create_datetime"] = item.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
            _data["update_datetime"] = item.update_datetime.strftime("%Y-%m-%d %H:%M:%S")
            return_data.append(_data)

        return DetailResponse(data={"data": return_data, "count": count}, msg="获取成功")


# 获取消息列表接口--消息中心
class MsgList(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="message-list",
        operation_description="获取消息列表接口--消息中心",
    )
    def get(self, request):
        token = request.headers["Authorization"]
        request_data = request.query_params
        page = int(request_data.get("page", 1))

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()
        username_obj = json.loads(username_obj)

        page_size = 5
        message_obj = MessageModel.objects
        message_obj = message_obj.filter(username=username_obj["username"])
        count = message_obj.count()
        res = message_obj.all()[
              page_size * (page - 1):page_size * page]

        return_data = []
        for item in res:
            _data = {}
            _data["id"] = item.id
            _data["ydh"] = item.ydh
            _data["third_ydh"] = item.third_ydh
            _data["fhdw"] = item.fhdw
            _data["shdw"] = item.shdw
            _data["start_time"] = item.start_time.strftime("%Y-%m-%d %H:%M:%S")
            _data["sign_time"] = item.sign_time.strftime("%Y-%m-%d %H:%M:%S")
            _data["temp_limit_max"] = item.temp_limit_max
            _data["temp_limit_min"] = item.temp_limit_min
            _data["temp_max"] = item.temp_max
            _data["temp_min"] = item.temp_min
            _data["remark"] = item.remark
            _data["type"] = item.type
            _data["status"] = item.status
            _data["create_datetime"] = item.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
            _data["update_datetime"] = item.update_datetime.strftime("%Y-%m-%d %H:%M:%S")
            return_data.append(_data)

        return DetailResponse(data={"data": return_data, "count": count}, msg="获取成功")


# 处理消息接口
class MessageAction(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="message-action",
        operation_description="处理消息接口",
    )
    def post(self, request):
        token = request.headers["Authorization"]
        id = request.data.get("id")

        if not id:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"admin_login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")


        message_info = MessageModel.objects.get(id=id)
        if not message_info:
            return ErrorResponse(code=4001, msg="数据不存在")

        MessageModel.objects.filter(id=id).update(status=2)



        return DetailResponse(data={}, msg="处理成功")


# 处理消息接口--催办
class MessageActionCb(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("获取成功")},
        security=[],
        operation_id="message-action",
        operation_description="处理消息接口---催办",
    )
    def post(self, request):
        token = request.headers["Authorization"]
        id = request.data.get("id")

        slwbr_ydh = request.data.get("slwbr_ydh")
        slwbr_cuswbno = request.data.get("slwbr_cuswbno")
        slwbr_fhdw = request.data.get("slwbr_fhdw")
        slwbr_shdw = request.data.get("slwbr_shdw")
        slwbr_thsj = request.data.get("slwbr_thsj")
        slwbr_qssj = request.data.get("slwbr_qssj")
        slwbr_wdmin = request.data.get("slwbr_wdmin")
        slwbr_wdmax = request.data.get("slwbr_wdmax")
        mintem = request.data.get("mintem")
        maxtem = request.data.get("maxtem")

        remark = ""
        type = 1 # 催办
        status = 1 # 未处理

        # 判断24小时内催办是否存在
        # 获取当前时间
        now = timezone.now()
        # 计算24小时前的时间
        twenty_four_hours_ago = now - timezone.timedelta(hours=24)

        message_info = MessageModel.objects.filter(ydh=slwbr_ydh).filter(type=1).filter(status=1).filter(create_datetime__gte=twenty_four_hours_ago)
        if message_info:
            return ErrorResponse(code=4000, msg="24小时内只能催办一次")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()
        username_obj = json.loads(username_obj)


        MessageModel.objects.create(
            ydh=slwbr_ydh,
            third_ydh=slwbr_cuswbno,
            fhdw=slwbr_fhdw,
            shdw=slwbr_shdw,
            start_time=slwbr_thsj,
            sign_time=slwbr_qssj,
            temp_limit_max=slwbr_wdmax,
            temp_limit_min=slwbr_wdmin,
            temp_max=maxtem,
            temp_min=mintem,
            remark=remark,
            status=status,
            type=type,
            username = username_obj["username"]
        )

        return DetailResponse(data={}, msg="处理成功")


# 消息接口 --- 审核
class MessagePass(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("操作成功")},
        security=[],
        operation_id="getway-bill",
        operation_description="消息接口 --- 审核",
    )
    def post(self, request):
        token = request.headers["Authorization"]
        slwbr_ydh = request.data.get("slwbr_ydh")
        type = request.data.get("type")

        if not slwbr_ydh or not type:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()
        username_obj = json.loads(username_obj)

        if type == 1: #审核通过
            payload = {'ydhList': [slwbr_ydh]}
        elif type == 2: #审核未通过
            payload = {'nopassedList': [slwbr_ydh]}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }

        response = requests.post('https://10.80.40.22:8443/apiv3/confirmwaybillyjdj', json=payload,
                                headers=headers, verify=False)
        rep_data = response.json()

        if type == 2 and rep_data["code"] == 200: #审核未通过

            slwbr_cuswbno = request.data.get("slwbr_cuswbno")
            slwbr_fhdw = request.data.get("slwbr_fhdw")
            slwbr_shdw = request.data.get("slwbr_shdw")
            slwbr_thsj = request.data.get("slwbr_thsj")
            slwbr_qssj = request.data.get("slwbr_qssj")
            slwbr_wdmin = request.data.get("slwbr_wdmin")
            slwbr_wdmax = request.data.get("slwbr_wdmax")
            mintem = request.data.get("mintem")
            maxtem = request.data.get("maxtem")

            remark = request.data.get("remark")
            type = 2  # 催办
            status = 1  # 未处理

            MessageModel.objects.create(
                ydh=slwbr_ydh,
                third_ydh=slwbr_cuswbno,
                fhdw=slwbr_fhdw,
                shdw=slwbr_shdw,
                start_time=slwbr_thsj,
                sign_time=slwbr_qssj,
                temp_limit_max=slwbr_wdmax,
                temp_limit_min=slwbr_wdmin,
                temp_max=maxtem,
                temp_min=mintem,
                remark=remark,
                status=status,
                type=type,
                username=username_obj["username"]
            )
        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})
        return DetailResponse(data=rep_data["data"],msg=rep_data["msg"])


# 消息接口 --- 转为待审核
class MessagePassToDsh(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("操作成功")},
        security=[],
        operation_id="getway-bill",
        operation_description="消息接口 --- 转为待审核",
    )
    def post(self, request):
        token = request.headers["Authorization"]
        slwbr_ydh = request.data.get("slwbr_ydh")

        if not slwbr_ydh:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        payload = {'ydhList': [slwbr_ydh]}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }

        response = requests.post('https://10.80.40.22:8443/apiv3/reversewaybillyjdj', json=payload,
                                headers=headers, verify=False)
        rep_data = response.json()

        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})
        return DetailResponse(data=rep_data["data"],msg=rep_data["msg"])


# 消息接口 --- 上传
class MessagePassUpload(APIView):
    authentication_classes = []
    permission_classes = []

    @swagger_auto_schema(
        responses={"200": openapi.Response("操作成功")},
        security=[],
        operation_id="getway-bill",
        operation_description="消息接口 --- 上传",
    )
    def post(self, request):
        token = request.headers["Authorization"]
        slwbr_ydh = request.data.get("slwbr_ydh")

        if not slwbr_ydh:
            return ErrorResponse(code=4000, msg="接口参数异常")

        redis_conn = get_redis_connection()
        username_obj = redis_conn.get(f"login_token:{token}")
        if not username_obj:
            return ErrorResponse(code=4001, msg="登录失败")

        username_obj = username_obj.decode()

        payload = {'ydhList': [slwbr_ydh]}
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }

        response = requests.post('https://10.80.40.22:8443/apiv3/uploadwaybillyjdj', json=payload,
                                headers=headers, verify=False)
        rep_data = response.json()

        if rep_data["code"] in (400, 401):
            return ErrorResponse(code=401, msg={"code": "token_not_valid", "msg": "登录失效，请重新登陆"})
        return DetailResponse(data=rep_data["data"],msg=rep_data["msg"])
